<template>
  <view class="post-detail-container">
    <!-- 主要内容区域 -->
    <scroll-view
      class="main-content"
      scroll-y
      @scrolltolower="loadMoreComments"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 帖子详情 -->
      <view class="post-detail modern-card">
        <!-- 用户信息 -->
        <view class="post-header">
          <view class="user-info" @click="handleUserProfile">
            <u-avatar
              :src="postDetail.userAvatar || '/static/images/default-avatar.png'"
              size="45"
              class="avatar-gradient"
            ></u-avatar>
            <view class="user-details">
              <text class="username">{{ postDetail.username || '用户' + postDetail.uid }}</text>
              <text class="post-time">{{ formatTime(postDetail.create_time) }}</text>
            </view>
          </view>
          <view class="post-actions">
            <u-icon name="more-dot-fill" color="#999" size="20" @click="showActionSheet"></u-icon>
          </view>
        </view>

        <!-- 帖子内容 -->
        <view class="post-content">
          <text class="post-title" v-if="postDetail.title">{{ postDetail.title }}</text>
          <text class="post-text">{{ postDetail.content }}</text>

          <!-- 话题标签 -->
          <view class="topic-tags" v-if="postDetail.topics && postDetail.topics.length > 0">
            <text
              class="topic-tag"
              v-for="topic in postDetail.topics"
              :key="topic"
              @click="handleTopicClick(topic)"
            >
              #{{ topic }}
            </text>
          </view>

          <!-- 图片展示 -->
          <view class="post-images" v-if="postDetail.mediaList && postDetail.mediaList.length > 0">
            <view
              class="image-grid"
              :class="'grid-' + Math.min(postDetail.mediaList.length, 3)"
            >
              <image
                v-for="(img, index) in postDetail.mediaList"
                :key="index"
                :src="img"
                class="post-image"
                mode="aspectFill"
                @click="previewImage(postDetail.mediaList, index)"
              ></image>
            </view>
          </view>

          <!-- 位置信息 -->
          <view class="post-location" v-if="postDetail.address">
            <u-icon name="map-pin" color="#999" size="14"></u-icon>
            <text class="location-text">{{ postDetail.address }}</text>
          </view>
        </view>

        <!-- 互动统计 -->
        <view class="interaction-stats">
          <view class="stats-left">
            <text class="stat-text">{{ postDetail.read_count || 0 }} 浏览</text>
            <text class="stat-text">{{ formatTime(postDetail.create_time) }}</text>
          </view>
          <view class="stats-right">
            <text class="stat-text" v-if="postDetail.likeCount > 0">{{ postDetail.likeCount }}人点赞</text>
          </view>
        </view>

        <!-- 互动按钮 -->
        <view class="interaction-buttons">
          <view class="interaction-btn" @click="handleLike">
            <u-icon
              :name="postDetail.isLiked ? 'heart-fill' : 'heart'"
              :color="postDetail.isLiked ? '#ff4757' : '#999'"
              size="20"
            ></u-icon>
            <text class="btn-text" :class="{ active: postDetail.isLiked }">
              {{ postDetail.isLiked ? '已点赞' : '点赞' }}
            </text>
          </view>
          <view class="interaction-btn" @click="handleComment">
            <u-icon name="chat" color="#999" size="20"></u-icon>
            <text class="btn-text">评论</text>
          </view>
          <view class="interaction-btn" @click="handleShare">
            <u-icon name="share" color="#999" size="20"></u-icon>
            <text class="btn-text">分享</text>
          </view>
          <view class="interaction-btn" @click="handleCollect">
            <u-icon
              :name="postDetail.isCollected ? 'star-fill' : 'star'"
              :color="postDetail.isCollected ? '#FFD700' : '#999'"
              size="20"
            ></u-icon>
            <text class="btn-text" :class="{ active: postDetail.isCollected }">
              {{ postDetail.isCollected ? '已收藏' : '收藏' }}
            </text>
          </view>
        </view>
      </view>

      <!-- 评论区域 -->
      <view class="comments-section">
        <view class="comments-header">
          <text class="comments-title">评论 {{ commentList.length }}</text>
          <view class="sort-options">
            <text
              class="sort-option"
              :class="{ active: commentSort === 'time' }"
              @click="changeCommentSort('time')"
            >时间</text>
            <text
              class="sort-option"
              :class="{ active: commentSort === 'hot' }"
              @click="changeCommentSort('hot')"
            >热度</text>
          </view>
        </view>

        <!-- 评论列表 -->
        <view class="comment-list">
          <view
            class="comment-item"
            v-for="comment in commentList"
            :key="comment.id"
          >
            <!-- 评论主体 -->
            <view class="comment-main">
              <u-avatar
                :src="comment.userAvatar || '/static/images/default-avatar.png'"
                size="35"
              ></u-avatar>
              <view class="comment-content">
                <view class="comment-header">
                  <text class="comment-username">{{ comment.username }}</text>
                  <text class="comment-time">{{ formatTime(comment.create_time) }}</text>
                </view>
                <text class="comment-text">{{ comment.content }}</text>

                <!-- 评论图片 -->
                <view class="comment-images" v-if="comment.images && comment.images.length > 0">
                  <image
                    v-for="(img, index) in comment.images"
                    :key="index"
                    :src="img"
                    class="comment-image"
                    mode="aspectFill"
                    @click="previewImage(comment.images, index)"
                  ></image>
                </view>

                <!-- 评论操作 -->
                <view class="comment-actions">
                  <view class="action-btn" @click="handleCommentLike(comment)">
                    <u-icon
                      :name="comment.isLiked ? 'heart-fill' : 'heart'"
                      :color="comment.isLiked ? '#ff4757' : '#999'"
                      size="14"
                    ></u-icon>
                    <text class="action-text">{{ comment.likeCount || 0 }}</text>
                  </view>
                  <view class="action-btn" @click="handleReply(comment)">
                    <u-icon name="chat" color="#999" size="14"></u-icon>
                    <text class="action-text">回复</text>
                  </view>
                </view>
              </view>
            </view>

            <!-- 回复列表 -->
            <view class="reply-list" v-if="comment.replies && comment.replies.length > 0">
              <view
                class="reply-item"
                v-for="reply in comment.replies"
                :key="reply.id"
              >
                <u-avatar
                  :src="reply.userAvatar || '/static/images/default-avatar.png'"
                  size="25"
                ></u-avatar>
                <view class="reply-content">
                  <view class="reply-header">
                    <text class="reply-username">{{ reply.username }}</text>
                    <text class="reply-target" v-if="reply.replyToUsername">
                      回复 {{ reply.replyToUsername }}
                    </text>
                    <text class="reply-time">{{ formatTime(reply.create_time) }}</text>
                  </view>
                  <text class="reply-text">{{ reply.content }}</text>

                  <view class="reply-actions">
                    <view class="action-btn" @click="handleReplyLike(reply)">
                      <u-icon
                        :name="reply.isLiked ? 'heart-fill' : 'heart'"
                        :color="reply.isLiked ? '#ff4757' : '#999'"
                        size="12"
                      ></u-icon>
                      <text class="action-text">{{ reply.likeCount || 0 }}</text>
                    </view>
                    <view class="action-btn" @click="handleReplyToReply(reply, comment)">
                      <u-icon name="chat" color="#999" size="12"></u-icon>
                      <text class="action-text">回复</text>
                    </view>
                  </view>
                </view>
              </view>

              <!-- 查看更多回复 -->
              <view class="more-replies" v-if="comment.replyCount > comment.replies.length">
                <text class="more-text" @click="loadMoreReplies(comment)">
                  查看更多 {{ comment.replyCount - comment.replies.length }} 条回复
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载更多评论 -->
        <view class="load-more" v-if="hasMoreComments">
          <u-loading-icon v-if="loadingComments" color="#667eea" size="20"></u-loading-icon>
          <text class="load-text">{{ loadingComments ? '加载中...' : '上拉加载更多评论' }}</text>
        </view>

        <!-- 没有评论 -->
        <view class="no-comments" v-if="!loadingComments && commentList.length === 0">
          <u-icon name="chat" color="#ccc" size="40"></u-icon>
          <text class="no-comments-text">还没有评论，快来抢沙发吧~</text>
        </view>
      </view>
    </scroll-view>

    <!-- 底部评论输入框 -->
    <view class="comment-input-bar" :style="{ paddingBottom: safeAreaBottom + 'px' }">
      <view class="input-container" v-if="isLoggedIn">
        <u-avatar
          :src="userInfo.avatar || '/static/images/default-avatar.png'"
          size="30"
        ></u-avatar>
        <view class="input-wrapper" @click="handleComment">
          <text class="input-placeholder">写评论...</text>
        </view>
        <view class="input-actions">
          <emoji-icon :size="22" color="#999" @click="handleEmojiClick"></emoji-icon>
          <u-icon name="camera" color="#999" size="22" @click="handleChooseImage"></u-icon>
        </view>
      </view>
      <view class="login-prompt" v-else @click="handleLogin">
        <u-icon name="account" color="#667eea" size="20"></u-icon>
        <text class="login-text">登录后参与评论</text>
      </view>
    </view>

    <!-- 评论输入弹窗 -->
    <u-popup
     :show="showCommentModal"
      mode="bottom"
      border-radius="20"
      :safe-area-inset-bottom="true"
    >
      <view class="comment-modal">
        <view class="modal-header">
          <text class="modal-title">{{ replyTarget ? '回复评论' : '写评论' }}</text>
          <u-icon name="close" color="#999" size="20" @click="closeCommentModal"></u-icon>
        </view>

        <!-- 回复目标 -->
        <view class="reply-target-info" v-if="replyTarget">
          <text class="target-text">回复 {{ replyTarget.username }}:</text>
          <text class="target-content">{{ replyTarget.content }}</text>
        </view>

        <!-- 评论输入 -->
        <view class="comment-input-section">
          <textarea
            v-model="commentForm.content"
            placeholder="写下你的评论..."
            class="comment-textarea"
            :maxlength="200"
            auto-height
            :focus="showCommentModal"
          ></textarea>
          <view class="char-count">
            <text class="count-text">{{ commentForm.content.length }}/200</text>
          </view>
        </view>

        <!-- 评论图片 -->
        <view class="comment-images-section" v-if="commentForm.images.length > 0">
          <view class="comment-images-grid">
            <view
              class="comment-image-item"
              v-for="(image, index) in commentForm.images"
              :key="index"
            >
              <image :src="image.url" class="comment-image" mode="aspectFill"></image>
              <view class="remove-image" @click="removeCommentImage(index)">
                <u-icon name="close" color="white" size="14"></u-icon>
              </view>
            </view>
          </view>
        </view>

        <!-- 评论操作 -->
        <view class="comment-modal-footer">
          <view class="footer-actions">
            <emoji-icon :size="24" color="#999" @click="handleEmojiPanelShow"></emoji-icon>
            <u-icon name="camera" color="#999" size="24" @click="chooseCommentImage"></u-icon>
          </view>
          <u-button
            type="primary"
            size="small"
            :custom-style="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none' }"
            :disabled="!commentForm.content.trim()"
            :loading="submittingComment"
            @click="submitComment"
          >
            {{ submittingComment ? '发送中...' : '发送' }}
          </u-button>
        </view>
      </view>
    </u-popup>

    <!-- 操作菜单 -->
    <u-action-sheet
      :list="actionSheetList"
      v-model="showActionSheet"
      @click="handleActionSheet"
    ></u-action-sheet>

    <!-- Toast提示 -->

  </view>
</template>

<script>
import { requireLogin, isLoggedIn } from '@/utils/auth'
import {getInfo,increaseReadCount,getComments} from '@/api/quanzi/post'
import {listPostComments} from "../../api/quanzi/post";
import EmojiIcon from '@/components/emoji-icon/emoji-icon.vue'

export default {
  components: {
    EmojiIcon
  },
  data() {
    return {
      postId: '',
      safeAreaBottom: 0,
      refreshing: false,
      loadingComments: false,
      hasMoreComments: true,
      commentPage: 1,
      commentPageSize: 10,
      commentSort: 'time',
      showCommentModal: false,
      showEmojiPanel: false,
      showActionSheet: false,
      submittingComment: false,
      isLoggedIn: false,

      // 用户信息
      userInfo: {
        avatar: 'https://cdn.uviewui.com/uview/album/1.jpg'
      },

      // 帖子详情
      postDetail: {},

      // 评论列表
      commentList: [],

      // 评论表单
      commentForm: {
        content: '',
        images: []
      },

      // 回复目标
      replyTarget: null,

      // 操作菜单
      actionSheetList: [
        { text: '举报', color: '#ff4757' },
        { text: '不感兴趣' },
        { text: '复制链接' }
      ]
    }
  },

  onLoad(options) {
    this.postId = options.id
    this.initPage()

    // 如果有评论操作参数，直接打开评论框
    if (options.action === 'comment') {
      setTimeout(() => {
        this.handleComment()
      }, 500)
    }
  },

  onShow() {
    this.checkLoginStatus()
  },

  methods: {
    // 检查登录状态
    checkLoginStatus() {
      this.isLoggedIn = isLoggedIn()
    },

    // 初始化页面
    async initPage() {
      const systemInfo = uni.getSystemInfoSync()
      this.safeAreaBottom = systemInfo.safeAreaInsets && systemInfo.safeAreaInsets.bottom || 0

      this.checkLoginStatus()
      await this.loadPostDetail()
      await this.loadComments()
    },

    // 加载帖子详情
    async loadPostDetail() {
      try {
        const res = await getInfo(this.postId)
        if (res.code === 200 && res.data) {
          this.postDetail = {
            id: res.data.id,
            uid: res.data.uid,
            username: res.data.username || '用户' + res.data.uid,
            userAvatar: res.data.userAvatar || '/static/images/default-avatar.png',
            title: res.data.title,
            content: res.data.content,
            topics: res.data.topics ? res.data.topics.split(',') : [],
            mediaList: res.data.media	 ? JSON.parse(res.data.media	) : [],
            address: res.data.address,
            create_time: res.data.createTime,
            read_count: res.data.readCount || 0,
            likeCount: res.data.likeCount || 0,
            commentCount: res.data.commentCount || 0,
            isLiked: res.data.isLiked || false,
            isCollected: res.data.isCollected || false
          }
        } else {
          this.showToast(res.msg || '加载帖子详情失败', 'error')
        }
      } catch (error) {
        console.error('加载帖子详情失败:', error)
        this.showToast('网络错误，请重试', 'error')
      }
    },

    // 加载评论列表
    async loadComments() {
      if (this.loadingComments) return

      this.loadingComments = true

      try {
        const params = {
          postId: this.postId,
          pageNum: this.commentPage,
          pageSize: this.commentPageSize,
          orderByColumn: this.commentSort === 'hot' ? 'like_count' : 'create_time',
          isAsc: 'desc'
        }

        const res = await listPostComments(this.postId,params)

        if (res.code === 200 && res.rows) {
          const comments = res.rows.map(item => ({
            id: item.id,
            username: item.username || '用户' + item.uid,
            userAvatar: item.userAvatar || '/static/images/default-avatar.png',
            content: item.content,
            images: item.images ? JSON.parse(item.images) : [],
            create_time: item.createTime,
            likeCount: item.likeCount || 0,
            isLiked: item.isLiked || false,
            replyCount: item.replyCount || 0,
            replies: item.replies || []
          }))

          if (this.commentPage === 1) {
            this.commentList = comments
          } else {
            this.commentList.push(...comments)
          }

          this.hasMoreComments = comments.length === this.commentPageSize
        } else {
          this.showToast(res.msg || '加载评论失败', 'error')
        }
      } catch (error) {
        console.error('加载评论失败:', error)
        this.showToast('网络错误，请重试', 'error')
      } finally {
        this.loadingComments = false
      }
    },

    // 生成模拟评论数据
    generateMockComments() {
      const comments = []
      const usernames = ['小明', '小红', '小李', '小王', '小张']
      const contents = [
        '拍得真好看！',
        '这个角度很棒',
        '春天的校园确实很美',
        '请问是用什么相机拍的？',
        '我也想去这里拍照'
      ]

      for (let i = 0; i < Math.min(this.commentPageSize, 5); i++) {
        const comment = {
          id: Date.now() + i,
          username: usernames[i % usernames.length],
          userAvatar: `https://cdn.uviewui.com/uview/album/${(i % 6) + 1}.jpg`,
          content: contents[i % contents.length],
          create_time: new Date(Date.now() - Math.random() * 3600000).toISOString(),
          likeCount: Math.floor(Math.random() * 10),
          isLiked: Math.random() > 0.7,
          replyCount: Math.floor(Math.random() * 3),
          replies: []
        }

        // 添加一些回复
        if (comment.replyCount > 0) {
          for (let j = 0; j < Math.min(comment.replyCount, 2); j++) {
            comment.replies.push({
              id: Date.now() + i * 100 + j,
              username: usernames[(i + j + 1) % usernames.length],
              userAvatar: `https://cdn.uviewui.com/uview/album/${((i + j + 1) % 6) + 1}.jpg`,
              content: '说得对！',
              replyToUsername: j === 0 ? comment.username : comment.replies[j-1].username,
              create_time: new Date(Date.now() - Math.random() * 1800000).toISOString(),
              likeCount: Math.floor(Math.random() * 5),
              isLiked: Math.random() > 0.8
            })
          }
        }

        comments.push(comment)
      }

      return comments
    },

    // 下拉刷新
    async onRefresh() {
      this.refreshing = true
      this.commentPage = 1
      await Promise.all([
        this.loadPostDetail(),
        this.loadComments()
      ])
      this.refreshing = false
    },

    // 加载更多评论
    async loadMoreComments() {
      if (!this.hasMoreComments) return

      this.commentPage++
      await this.loadComments()
    },

    // 切换评论排序
    changeCommentSort(sort) {
      this.commentSort = sort
      this.commentPage = 1
      this.loadComments()
    },

    // 格式化时间
    formatTime(timeStr) {
      const time = new Date(timeStr)
      const now = new Date()
      const diff = now - time

      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
      if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
      if (diff < 604800000) return Math.floor(diff / 86400000) + '天前'

      return time.toLocaleDateString()
    },

    // 事件处理方法
    handleUserProfile() {
      this.$tab.navigateTo(`/pages/user/profile?uid=${this.postDetail.uid}`)
    },

    handleTopicClick(topic) {
      this.$tab.navigateTo(`/pages/search/index?keyword=${encodeURIComponent('#' + topic)}`)
    },

    previewImage(images, current) {
      // 确保传入的 current 是索引或者图片 URL
      const currentImage = typeof current === 'number' ? images[current] : current;
      
      uni.previewImage({
        urls: images,
        current: currentImage,
        indicator: 'number', // 显示页码指示器
        loop: true, // 允许循环预览
        success: () => {
          console.log('图片预览成功');
        },
        fail: (err) => {
          console.error('图片预览失败:', err);
          this.showToast('图片预览失败', 'error');
        }
      });
    },

    handleLike() {
      if (isLoggedIn()) {
        this.postDetail.isLiked = !this.postDetail.isLiked
        this.postDetail.likeCount += this.postDetail.isLiked ? 1 : -1
        this.showToast(this.postDetail.isLiked ? '点赞成功' : '取消点赞', 'success')
      } else {
        this.showLoginTip('点赞')
      }
    },

    handleComment() {
      if (isLoggedIn()) {
        this.showCommentModal = true
      } else {
        this.showLoginTip('发表评论')
      }
    },

    handleShare() {
      // 分享功能不需要登录
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 0,
        href: `https://example.com/post/${this.postId}`,
        title: this.postDetail.title || '分享帖子',
        summary: this.postDetail.content,
        imageUrl: this.postDetail.mediaList && this.postDetail.mediaList[0] || ''
      })
    },

    handleCollect() {
      if (isLoggedIn()) {
        this.postDetail.isCollected = !this.postDetail.isCollected
        this.showToast(this.postDetail.isCollected ? '收藏成功' : '取消收藏', 'success')
      } else {
        this.showLoginTip('收藏')
      }
    },

    handleCommentLike(comment) {
      if (isLoggedIn()) {
        comment.isLiked = !comment.isLiked
        comment.likeCount += comment.isLiked ? 1 : -1
      } else {
        this.showLoginTip('点赞评论')
      }
    },

    handleReply(comment) {
      if (isLoggedIn()) {
        this.replyTarget = comment
        this.showCommentModal = true
      } else {
        this.showLoginTip('回复评论')
      }
    },

    handleReplyLike(reply) {
      if (isLoggedIn()) {
        reply.isLiked = !reply.isLiked
        reply.likeCount += reply.isLiked ? 1 : -1
      } else {
        this.showLoginTip('点赞回复')
      }
    },

    handleReplyToReply(reply, parentComment) {
      if (isLoggedIn()) {
        this.replyTarget = {
          ...reply,
          parentCommentId: parentComment.id
        }
        this.showCommentModal = true
      } else {
        this.showLoginTip('回复')
      }
    },

    loadMoreReplies(comment) {
      // 加载更多回复
      this.showToast('加载更多回复功能开发中', 'info')
    },

    handleActionSheet(index) {
      const actions = ['举报', '不感兴趣', '复制链接']
      const action = actions[index]

      switch (action) {
        case '举报':
          this.showToast('举报功能开发中', 'info')
          break
        case '不感兴趣':
          this.showToast('已标记为不感兴趣', 'success')
          break
        case '复制链接':
          uni.setClipboardData({
            data: `https://example.com/post/${this.postId}`,
            success: () => {
              this.showToast('链接已复制', 'success')
            }
          })
          break
      }
    },

    // 处理表情点击
    handleEmojiClick() {
      if (isLoggedIn()) {
        this.showEmojiPanel = true;
      } else {
        this.showLoginTip('使用表情');
      }
    },

    // 处理表情面板显示
    handleEmojiPanelShow() {
      this.showEmojiPanel = true;
    },

    // 处理登录
    handleLogin() {
      uni.navigateTo({
        url: '/pages/login'
      });
    },
    
    // 显示登录提示
    showLoginTip(action = '此操作') {
      uni.showModal({
        title: '提示',
        content: `${action}需要登录，是否前往登录？`,
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login'
            })
          }
        }
      })
    },

    // 评论相关方法
    closeCommentModal() {
      this.showCommentModal = false
      this.replyTarget = null
      this.commentForm = {
        content: '',
        images: []
      }
    },

    // 处理选择图片
    handleChooseImage() {
      if (isLoggedIn()) {
        this.chooseCommentImage();
      } else {
        this.showLoginTip('上传图片');
      }
    },
    
    async chooseCommentImage() {
      try {
        const res = await uni.chooseImage({
          count: 3 - this.commentForm.images.length,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        })

        for (let tempFilePath of res.tempFilePaths) {
          await this.uploadCommentImage(tempFilePath)
        }
      } catch (error) {
        console.error('选择图片失败:', error)
      }
    },

    async uploadCommentImage(filePath) {
      try {
        // 模拟上传
        this.commentForm.images.push({
          url: filePath,
          id: Date.now()
        })

        this.showToast('图片上传成功', 'success')
      } catch (error) {
        this.showToast('图片上传失败', 'error')
      }
    },

    removeCommentImage(index) {
      this.commentForm.images.splice(index, 1)
    },

    async submitComment() {
      if (!this.commentForm.content.trim()) {
        this.showToast('请输入评论内容', 'error')
        return
      }

      this.submittingComment = true

      try {
        // 构建评论数据
        const commentData = {
          postId: this.postId,
          content: this.commentForm.content.trim(),
          images: this.commentForm.images.map(img => img.url),
          replyToId: this.replyTarget?.id,
          parentCommentId: this.replyTarget?.parentCommentId || this.replyTarget?.id
        }

        // 这里应该调用API提交评论
        // const res = await this.$api.submitComment(commentData)

        // 模拟提交成功
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 添加到评论列表
        const newComment = {
          id: Date.now(),
          username: '我',
          userAvatar: this.userInfo.avatar,
          content: this.commentForm.content,
          images: this.commentForm.images.map(img => img.url),
          create_time: new Date().toISOString(),
          likeCount: 0,
          isLiked: false,
          replies: []
        }

        if (this.replyTarget) {
          // 如果是回复，添加到对应评论的回复列表
          const parentComment = this.commentList.find(c => c.id === (this.replyTarget.parentCommentId || this.replyTarget.id))
          if (parentComment) {
            const newReply = {
              ...newComment,
              replyToUsername: this.replyTarget.username
            }
            parentComment.replies.push(newReply)
            parentComment.replyCount = (parentComment.replyCount || 0) + 1
          }
        } else {
          // 如果是新评论，添加到评论列表开头
          this.commentList.unshift(newComment)
        }

        // 更新帖子评论数
        this.postDetail.commentCount = (this.postDetail.commentCount || 0) + 1

        this.showToast('评论成功', 'success')
        this.closeCommentModal()

      } catch (error) {
        console.error('提交评论失败:', error)
        this.showToast('评论失败，请重试', 'error')
      } finally {
        this.submittingComment = false
      }
    },

    showToast(title, type = 'default') {
      // 使用 uView 2.0 的 toast 方法
      this.$u.toast(title)
    }
  }
}
</script>

<style lang="scss" scoped>
.post-detail-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 60px;
}

.main-content {
  height: calc(100vh - 60px);
  padding: 15px;
}

.post-detail {
  margin-bottom: 15px;
  padding: 20px;

  .post-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .user-details {
        .username {
          font-size: 15px;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 4px;
        }

        .post-time {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }

  .post-content {
    .post-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      line-height: 1.4;
      margin-bottom: 10px;
      display: block;
    }

    .post-text {
      font-size: 15px;
      color: #666;
      line-height: 1.6;
      margin-bottom: 15px;
      display: block;
    }

    .topic-tags {
      margin-bottom: 15px;

      .topic-tag {
        display: inline-block;
        color: #667eea;
        font-size: 14px;
        margin-right: 10px;
        margin-bottom: 5px;

        &:hover {
          text-decoration: underline;
        }
      }
    }

    .post-images {
      margin-bottom: 15px;

      .image-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        &.grid-1 .post-image {
          width: 100%;
          height: 250px;
        }

        &.grid-2 .post-image {
          width: calc(50% - 4px);
          height: 150px;
        }

        &.grid-3 .post-image {
          width: calc(33.33% - 5.33px);
          height: 120px;
        }

        .post-image {
          border-radius: 12px;
        }
      }
    }

    .post-location {
      display: flex;
      align-items: center;
      gap: 6px;
      margin-bottom: 15px;

      .location-text {
        font-size: 13px;
        color: #999;
      }
    }
  }

  .interaction-stats {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 15px;

    .stats-left, .stats-right {
      display: flex;
      gap: 15px;

      .stat-text {
        font-size: 12px;
        color: #999;
      }
    }
  }

  .interaction-buttons {
    display: flex;
    justify-content: space-around;

    .interaction-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 6px;
      padding: 8px;

      .btn-text {
        font-size: 12px;
        color: #999;

        &.active {
          color: #667eea;
          font-weight: 600;
        }
      }
    }
  }
}

.comments-section {
  .comments-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: white;
    border-radius: 15px;
    margin-bottom: 15px;

    .comments-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .sort-options {
      display: flex;
      gap: 15px;

      .sort-option {
        font-size: 14px;
        color: #999;
        padding: 5px 10px;
        border-radius: 12px;

        &.active {
          color: #667eea;
          background: rgba(102, 126, 234, 0.1);
          font-weight: 600;
        }
      }
    }
  }

  .comment-list {
    .comment-item {
      background: white;
      border-radius: 15px;
      padding: 15px;
      margin-bottom: 10px;

      .comment-main {
        display: flex;
        gap: 12px;

        .comment-content {
          flex: 1;

          .comment-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 8px;

            .comment-username {
              font-size: 14px;
              font-weight: 600;
              color: #333;
            }

            .comment-time {
              font-size: 12px;
              color: #999;
            }
          }

          .comment-text {
            font-size: 14px;
            color: #666;
            line-height: 1.5;
            margin-bottom: 10px;
            display: block;
          }

          .comment-images {
            display: flex;
            gap: 8px;
            margin-bottom: 10px;

            .comment-image {
              width: 80px;
              height: 80px;
              border-radius: 8px;
            }
          }

          .comment-actions {
            display: flex;
            gap: 20px;

            .action-btn {
              display: flex;
              align-items: center;
              gap: 4px;

              .action-text {
                font-size: 12px;
                color: #999;
              }
            }
          }
        }
      }

      .reply-list {
        margin-top: 15px;
        padding-left: 47px;

        .reply-item {
          display: flex;
          gap: 10px;
          margin-bottom: 12px;

          .reply-content {
            flex: 1;

            .reply-header {
              display: flex;
              align-items: center;
              gap: 8px;
              margin-bottom: 6px;

              .reply-username {
                font-size: 13px;
                font-weight: 600;
                color: #333;
              }

              .reply-target {
                font-size: 13px;
                color: #667eea;
              }

              .reply-time {
                font-size: 11px;
                color: #999;
              }
            }

            .reply-text {
              font-size: 13px;
              color: #666;
              line-height: 1.4;
              margin-bottom: 8px;
              display: block;
            }

            .reply-actions {
              display: flex;
              gap: 15px;

              .action-btn {
                display: flex;
                align-items: center;
                gap: 3px;

                .action-text {
                  font-size: 11px;
                  color: #999;
                }
              }
            }
          }
        }

        .more-replies {
          text-align: center;
          padding: 8px 0;

          .more-text {
            font-size: 13px;
            color: #667eea;
          }
        }
      }
    }
  }

  .load-more, .no-comments {
    text-align: center;
    padding: 30px 20px;

    .load-text, .no-comments-text {
      font-size: 14px;
      color: #999;
      margin-top: 10px;
      display: block;
    }
  }
}

.comment-input-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid #f0f0f0;
  padding: 10px 15px;

  .input-container {
    display: flex;
    align-items: center;
    gap: 12px;

    .input-wrapper {
      flex: 1;
      background: #f8f9fa;
      border-radius: 20px;
      padding: 10px 15px;

      .input-placeholder {
        font-size: 14px;
        color: #999;
      }
    }

    .input-actions {
      display: flex;
      gap: 12px;
    }
  }

  .login-prompt {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    background: rgba(102, 126, 234, 0.1);
    border-radius: 20px;
    padding: 12px 20px;

    .login-text {
      font-size: 14px;
      color: #667eea;
      font-weight: 500;
    }
  }
}

.comment-modal {
  padding: 20px;
  max-height: 70vh;

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .modal-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }

  .reply-target-info {
    background: #f8f9fa;
    padding: 10px 15px;
    border-radius: 10px;
    margin-bottom: 15px;

    .target-text {
      font-size: 12px;
      color: #667eea;
      display: block;
      margin-bottom: 5px;
    }

    .target-content {
      font-size: 13px;
      color: #666;
      display: block;
    }
  }

  .comment-input-section {
    position: relative;
    margin-bottom: 15px;

    .comment-textarea {
      width: 100%;
      min-height: 80px;
      padding: 12px 15px;
      border: 1px solid #e0e0e0;
      border-radius: 12px;
      font-size: 14px;
      line-height: 1.5;
      background: #f8f9fa;
      resize: none;
    }

    .char-count {
      position: absolute;
      bottom: 8px;
      right: 12px;

      .count-text {
        font-size: 11px;
        color: #999;
      }
    }
  }

  .comment-images-section {
    margin-bottom: 15px;

    .comment-images-grid {
      display: flex;
      gap: 8px;

      .comment-image-item {
        position: relative;
        width: 60px;
        height: 60px;

        .comment-image {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }

        .remove-image {
          position: absolute;
          top: -5px;
          right: -5px;
          width: 20px;
          height: 20px;
          border-radius: 10px;
          background: rgba(255, 71, 87, 0.8);
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }

  .comment-modal-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .footer-actions {
      display: flex;
      gap: 15px;
    }
  }
}
</style>
